package leetcode.N1_N100;

import leetcode.comm.ListNode;

/**
 * @author xiwai [hww282306@alibaba-inc.com]
 * @version 1.0
 * @date 2020/10/13 10:23 上午
 */
public class N24 {

    public ListNode swapPairs(ListNode head) {
        ListNode left = head;
        if (left == null) {
            return head;
        }
        ListNode right = head.next;
        if (right == null)  {
            return head;
        }
        // 先做第一次变换
        left.next = right.next;
        right.next = left;

        // 重置表头指针 用于返回
        head = right;

        // 开始循环
        ListNode last = left;
        left = last.next;
        if (left == null) {
            return head;
        }
        right = left.next;

        while (right != null) {
            // 变换位置
            last.next = right;
            left.next = right.next;
            right.next = left;

            // 重新赋值
            last = left;
            left = last.next;
            if (left == null) {
                break;
            }
            right = left.next;
        }
        return head;
    }

}
